package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单 -- 最终目的，将用户订单数据存入表中
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional //开启事务 -- 设计到两张表
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 查询地址数据
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 查询用户数据
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }
        // 查询购物车列表
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(userId);
        if (shoppingCartList == null && shoppingCartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 补充下单表的数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(System.currentTimeMillis() + "");//订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);//获取用户id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());//获取地址信息中的电话
        orders.setAddress(
                addressBook.getProvinceName() +
                        addressBook.getCityName() +
                        addressBook.getDistrictName() +
                        addressBook.getDetail()
        );//设置详细地址
        orders.setConsignee(addressBook.getConsignee());//收货人名字
        orders.setUserName(user.getName());// 下单人姓名
        // 存入订单数据
        ordersMapper.insert(orders);
        // 补充订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        // 构造订单明细数据
        // 循环构造购物车列表数据，构造订单明细
        shoppingCartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            // 关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        // 批量插入订单明细数据
        ordersDetailMapper.insertBatch(orderDetailList);
        // 清空购物车
        shoppingCartMapper.cleanByUserId(userId);
        // 构造ordersubmitvo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())

                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.getById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));

        ////////////////////////////模拟支付成功
//业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //     给管理员发布来单提醒的消息
        HashMap<String, Object> returnMessage = new HashMap<>();
        returnMessage.put("type", 1);
        returnMessage.put("orderId", outTradeNo);
        returnMessage.put("content", "订单号" + outTradeNo);

        webSocketServer.sendToAllClient(
                JSON.toJSONString(returnMessage)
        );


    }

    /**
     * 分页查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {

        // 查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = ordersMapper.page(ordersPageQueryDTO);
        List<Orders> ordersList = page.getResult();
        // 补充detail数据
        ordersList.forEach(orders -> {
            List<OrderDetail> orderDetailList = ordersDetailMapper.getMsgsByOrderId(orders.getId());
            orders.setOrderDetailList(orderDetailList);
        });
        //     返回查询结果
        return new PageResult(page.getTotal(), ordersList);
    }

    /**
     * 查询订单详情 ，根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Orders ordersDetail(Long id) {
        // 查询并返回数据
        Orders orders = ordersMapper.getMsgById(id);
        orders.setOrderDetailList(
                ordersDetailMapper.getMsgsByOrderId(id)
        );
        return orders;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrders(Long id) {
        //     补充数据
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        //     更新数据表
        ordersMapper.changeStatus(orders);

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 查询再来一单的订单数据
        Orders orders = ordersDetail(id);
        // 修改数据
        orders.setId(null);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//支付状态 0未支付 1已支付 2退款
        orders.setNumber(System.currentTimeMillis() + "");
        //     保存
        //     保存订单
        ordersMapper.insert(orders);
        // 设置orderid在orderdetail中
        orders.getOrderDetailList().forEach(orderDetail -> {
            orderDetail.setOrderId(orders.getId());
        });
        //     保存订单详细
        ordersDetailMapper.insertBatch(orders.getOrderDetailList());
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 收集数据
        return ordersMapper.statistics();
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(ordersConfirmDTO.getId());
        //     更新数据表
        ordersMapper.changeStatus(orders);
    }

    /**
     * 拒单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersConfirmDTO.getRejectionReason());
        orders.setId(ordersConfirmDTO.getId());
        //     更新数据表
        ordersMapper.changeStatus(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setId(ordersCancelDTO.getId());
        //     更新数据表
        ordersMapper.changeStatus(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setId(id);
        //     更新数据表
        ordersMapper.changeStatus(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.COMPLETED);
        orders.setId(id);
        //     更新数据表
        ordersMapper.changeStatus(orders);
    }

    /**
     * 用户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = ordersMapper.getMsgById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于WebSocket实现催单
        Map<String,Object> map = new HashMap();
        map.put("type", 2);
        //2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
